#include "gamesetup.h"
#include "playersetup.h"
#include "player.h"
#include "gamemanager.h"
#include <QSpinBox>
#include <QLabel>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QPushButton>
#include <QGridLayout>

GameSetup::GameSetup(GameManager *game, QWidget *parent) : QWidget(parent)
{
	m_game = game;
	m_nPlayersLabel = new QLabel("Number of players:");
	m_nPlayersSpinBox = new QSpinBox();
	m_playersLayout = new QGridLayout;
	connect(m_nPlayersSpinBox, SIGNAL(valueChanged(int)),
		this, SLOT(nPlayersChanged(int)));
	m_nPlayersSpinBox->setRange(2, 10);
	m_nPlayersSpinBox->setValue(4);
	m_startButton = new QPushButton("Start Game");
	connect(m_startButton, SIGNAL(clicked()), this, SLOT(setupPlayers()));
	
	setupGui();
}

void GameSetup::nPlayersChanged(int value)
{
	if (value != m_players.size()) {
		while (value < m_players.size()) {
			m_playersLayout->removeWidget(m_players.last());
			delete m_players.last();
			m_players.removeLast();
		}
		while (value > m_players.size()) {
			if (m_players.empty()) {
				m_players.append(new PlayerSetup(true));
			} else {
				m_players.append(new PlayerSetup);
			}
			m_playersLayout->addWidget(m_players.last(), m_players.size(), 0);
		}
	}
}

void GameSetup::setupPlayers()
{
	QListIterator<PlayerSetup*> i(m_players);
	while (i.hasNext()) {
		PlayerSetup *setup = i.next();
		m_game->addPlayer(setup->getName(), setup->getComputer());
	}
	
	emit setupDone();
}

void GameSetup::setupGui()
{
	QHBoxLayout *nPlayersLayout = new QHBoxLayout;
	nPlayersLayout->addWidget(m_nPlayersLabel);
	nPlayersLayout->addWidget(m_nPlayersSpinBox);
	nPlayersLayout->addStretch();
	
	QVBoxLayout *layout = new QVBoxLayout;
	layout->addLayout(nPlayersLayout);
	layout->addLayout(m_playersLayout);
	layout->addStretch();
	
	QHBoxLayout *startLayout = new QHBoxLayout;
	startLayout->addStretch();
	startLayout->addWidget(m_startButton);
	layout->addLayout(startLayout);
	
	setLayout(layout);
}
